package com.jd.fruit.model.admin.shop;

import java.util.List;

import com.alibaba.fastjson.JSONObject;
import com.jd.fruit.common.annotation.Table;
import com.jd.fruit.common.model.BaseModel;
import com.jd.fruit.common.util.StringUtil;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;

/**
 * 商品sku
 * 
 * @author lishunfeng
 * 
 */
@SuppressWarnings("serial")
@Table("t_goods_sku")
public class GoodsSku extends BaseModel<GoodsSku> {
	public static final GoodsSku dao = new GoodsSku();

	/**
	 * 保存商品SKU
	 * 
	 * @param role
	 */
	public void save(GoodsSku goodsSku) {
		try {
			goodsSku.set("id", StringUtil.getKey());
			goodsSku.save();
		} catch (Exception e) {
			throw new RuntimeException("商品Sku保存异常！", e);
		}
	}

	/**
	 * 删除商品所有关联的SKU数据
	 * 
	 * @param roleid
	 */
	public void delSkuRelationGoods(String goodsid) {
		Db.deleteById("t_goods_sku", "goods_id", goodsid);
	}
	
	/**
	 * 根据商品ID查询出对应SKU
	 * @param goodsId
	 * @return
	 */
	public List<GoodsSku> listByGoods(String goodsId) {
		String sql = "SELECT * FROM `t_goods_sku` WHERE `goods_id`=?";
		return this.find(sql, goodsId);
	}
	
	/**
	 * 根据商品自增ID查询出对应SKU
	 * @param goodsId
	 * @return
	 */
	public List<GoodsSku> listByGoodsNo(String goodsNo) {
		String sql = "SELECT tgs.* FROM `t_goods` tg JOIN t_goods_sku tgs ON tgs.`goods_id` =tg.`id` WHERE tg.goods_no=?";
		return this.find(sql, goodsNo);
	}
	
	/**
	 * 获取商品图片
	 * @param string
	 * @return
	 */
	public List<GoodsSku> listImage(String goodsId) {
		String sql="SELECT id,`goods_image` FROM `t_goods_sku` WHERE `goods_id` =?";
		return this.find(sql, goodsId);
	}
	
	@Override
	public void initWhere() {
		// TODO Auto-generated method stub

	}
	
	/**
	 * 查询商品价格库存信息
	 * @param goodsId
	 * @param attrStr
	 * @return
	 */
	public String goodsAttrVal(String goodsId,String attrStr) { 
		StringBuffer sql=new StringBuffer("SELECT * FROM `t_goods_sku` WHERE goods_id=? ");
		if(StrKit.notBlank(attrStr)){
			sql.append(" AND `attr_value` =? ");
		}
		Record val=Db.findFirst(sql.toString(), goodsId,attrStr);
		return val!=null?val.toJson():"";
	}
	
}
